package com.adinnet.api.dict.service.impl;

import com.adinnet.api.dict.model.form.DictForm;
import com.adinnet.api.dict.model.Dict;
import com.adinnet.api.dict.mapper.DictMapper;
import com.adinnet.api.dict.service.DictService;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 字典 服务实现类
 * </p>
 *
 * @author sunjianbo
 * @since 2019-11-05
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    public PageResp<Dict> queryList(DictForm form) {
        Page<Dict> page = new Page<>(form.getPage(), form.getLimit());
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(form.getDictCode())) {
            queryWrapper.eq("dict_code", form.getDictCode());
        }
        if(StringUtils.isNotEmpty(form.getParentId())){
            queryWrapper.eq("parent_id", form.getParentId());
        }else{
            queryWrapper.isNull("parent_id");
        }
        IPage<Dict> iPage = baseMapper.selectPage(page, queryWrapper);
        return new PageResp<>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public String getDictNamesByIds(String ids) {
        return baseMapper.getDictNamesByIds(ids);
    }

    @Override
    public Dict getDictByDictCode(String dictCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dict_code", dictCode);
        List<Dict> dictList= baseMapper.selectList(queryWrapper);
        if(dictList!=null && dictList.size()>0){
            return dictList.get(0);
        }else{
            return null;
        }
    }

    @Override
    public Dict getDictByRemark(String remark) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("remark", remark);
        List<Dict> dictList= baseMapper.selectList(queryWrapper);
        if(dictList!=null && dictList.size()>0){
            return dictList.get(0);
        }else{
            return null;
        }
    }

    @Override
    public Integer updateDictNameById(String dictName, Integer id) {
        return baseMapper.updateDictNameById(dictName,id);
    }

    @Override
    public Integer updateDictNameByDictCode(String dictName,String dictCode) {
        return baseMapper.updateDictNameByDictCode(dictName,dictCode);
    }

    @Override
    public JsonResult updateDict(Dict dict) {
        Integer updateCount = baseMapper.updateById(dict);
        if (updateCount == 0) {
            return JsonResult.error("修改失败");
        }
        return JsonResult.ok("修改成功");
    }
}
